package com.guomei.controller.curse;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.guomei.utils.PageData;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guomei.bean.User;
import com.guomei.bean.curse.Course;
import com.guomei.bean.curse.domain.CourseDistributerRel;
import com.guomei.bean.curse.vo.CourseDistributerRelDTO;
import com.guomei.bean.curse.vo.CourseDistributerRelVo;
import com.guomei.bean.curse.vo.DistributorCourseRevenueVo;
import com.guomei.mapper.UserMapper;
import com.guomei.mapper.curse.CourseDistributerRelMapper;
import com.guomei.mapper.curse.CourseMapper;
import com.guomei.utils.Result;

import lombok.extern.slf4j.Slf4j;


@RestController
@RequestMapping("/api1/courseDistributerRel")
@Slf4j
public class CourseDistributerRelController {
    

    @Resource
    CourseDistributerRelMapper courseDistributerRelMapper;

    @Resource
    CourseMapper courseMapper;

    @Resource
    UserMapper userMapper;


    @PostMapping("/select")
    public Result<?> select(@RequestBody CourseDistributerRelDTO dto) {

        QueryWrapper<CourseDistributerRel> wrapper = new QueryWrapper<>();

        if (dto.getCourseId() != null) {
            wrapper.eq("course_id", dto.getCourseId());

        }

        if (dto.getStatus() != null) {
            wrapper.eq("status", dto.getStatus());
        }

        if (dto.getTeacherId() != null) {
            wrapper.eq("teacher_id", dto.getTeacherId());
        }

        if (dto.getUserId() != null) {
            // DTO 中字段名为 userId，实际含义为分销员ID，对应表字段 distributer_id
            wrapper.eq("distributer_id", dto.getUserId());
        }

        if (dto.getIds() != null) {
            wrapper.in("id", dto.getIds());
        }

        List<CourseDistributerRel> items = courseDistributerRelMapper.selectList(wrapper);
        List<CourseDistributerRelVo> vos = new ArrayList<>();
        List<Long> courseIds = new ArrayList<>();
        List<Long> distributorIds = new ArrayList<>();
        
        for(int i = 0; i < items.size(); i++) {
            CourseDistributerRelVo vo = new CourseDistributerRelVo();
            CourseDistributerRel item = items.get(i);
            vo.setCode(item.getCode());
            vo.setId(item.getId());
            vo.setCreatedTime(item.getCreatedTime());
            vo.setUpdatedTime(item.getUpdatedTime());
            vo.setDistributionRatio(item.getDistributionRatio());
            vo.setStatus(item.getStatus());
            vo.setDistributerId(item.getDistributerId());
            vo.setCourseId(item.getCourseId());
            vo.setTeacherId(item.getTeacherId());
            courseIds.add(item.getCourseId());
            distributorIds.add(item.getDistributerId());
            vos.add(vo);
        }

        List<Course> courses = courseMapper.selectByIds(courseIds);
        List<User> distributors = userMapper.selectByAll(distributorIds);

        java.util.Map<Long, Course> courseById = new java.util.HashMap<>();
        for (int i = 0; i < courses.size(); i++) {
            Course c = courses.get(i);
            if (c != null && c.getId() != null) {
                courseById.put(c.getId(), c);
            }
        }

        java.util.Map<Long, User> distributorById = new java.util.HashMap<>();
        for (int i = 0; i < distributors.size(); i++) {
            User u = distributors.get(i);
            if (u != null && u.getId() != null) {
                distributorById.put(u.getId(), u);
            }
        }

        for (int i = 0; i < vos.size(); i++) {
            CourseDistributerRelVo vo = vos.get(i);
            vo.setCourse(courseById.get(vo.getCourseId()));
            vo.setDistributor(distributorById.get(vo.getDistributerId()));
        }
        // List<Course> courses = new ArrayList();


        PageData<CourseDistributerRelVo> data = new PageData<>();

        data.setData(vos);

        Long count = courseDistributerRelMapper.selectCount(wrapper);

        data.setTotal(count);

        data.setPageNum(dto.getPageNum());
        data.setPageSize(dto.getPageSize());

        return Result.success(data);
    }


    @PostMapping("/save")
    public Result<?> save(@RequestBody CourseDistributerRel rel) {

        QueryWrapper<CourseDistributerRel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("distributer_id", rel.getDistributerId());
        queryWrapper.eq("course_id", rel.getCourseId());
        CourseDistributerRel existing = courseDistributerRelMapper.selectOne(queryWrapper);
        Course course = courseMapper.selectById(rel.getCourseId());
        rel.setTeacherId(course.getTeacherId());

        // 处理分销比例，如果为null则设置默认值
        if (rel.getDistributionRatio() == null) {
            log.warn("分销比例为空，使用默认值0.00: distributerId={}, courseId={}", 
                rel.getDistributerId(), rel.getCourseId());
            rel.setDistributionRatio(java.math.BigDecimal.ZERO);
        }

        if (existing != null) {
            // return Result.error("该分销关系已存在");
            courseDistributerRelMapper.updateById(rel);
            return Result.success(rel);
        }

        courseDistributerRelMapper.insert(rel);
        return Result.success(rel);
    }

    @DeleteMapping("/dropByIds")
    public Result<?>  dropByIds(@RequestBody List<Long> ids) {

        courseDistributerRelMapper.deleteBatchIds(ids);
        return Result.success();
    }

    /**
     * 查询分销老师的课程收益列表（带分销统计）
     * 可以查询分销老师卖了哪些课，有多少收益，分销比例和分销码
     */
    @PostMapping("/selectDistributorCourseRevenue")
    public Result<?> selectDistributorCourseRevenue(@RequestBody CourseDistributerRelDTO dto) {
        if (dto.getUserId() == null) {
            return Result.error("分销老师ID不能为空");
        }
        
        List<DistributorCourseRevenueVo> list = courseDistributerRelMapper.selectDistributorCourseRevenue(dto.getUserId());
        return Result.success(list);
    }

    /**
     * 根据分销码查询关系
     */
    @PostMapping("/selectByCode")
    public Result<?> selectByCode(@RequestBody CourseDistributerRelDTO dto) {
        if (dto.getCode() == null || dto.getCode().isEmpty()) {
            return Result.error("分销码不能为空");
        }
        
        CourseDistributerRel rel = courseDistributerRelMapper.selectByCode(dto.getCode());
        return Result.success(rel);
    }

    /**
     * 根据分销老师ID和课程ID查询关系
     */
    @PostMapping("/selectByDistributorAndCourse")
    public Result<?> selectByDistributorAndCourse(@RequestBody CourseDistributerRelDTO dto) {
        if (dto.getUserId() == null || dto.getCourseId() == null) {
            return Result.error("分销老师ID和课程ID不能为空");
        }
        
        CourseDistributerRel rel = courseDistributerRelMapper.selectByDistributorAndCourse(dto.getUserId(), dto.getCourseId());
        return Result.success(rel);
    }
}
